//
//  MyDrawView.swift
//  SmartPenSwift
//
//  Created by tql on 2021/2/23.
//

import UIKit

public protocol getDrawImageDelegate : NSObjectProtocol {
    func  getDrawImage(_ drawImage : UIImage?) -> Void ;
}

class MyDrawView: UIView {
    var insideColor : UIColor = .black
    
    var strokeColor : UIColor  {
        get{
            return insideColor
        }set{
            insideColor = newValue
        }
    }
    
    weak open var delegate : getDrawImageDelegate?
     
    var hasDraw : Bool = false
    var drawImage : UIImage?
    var isChangePage : Bool = false
    
    func erase() -> Void {
        pageArray.removeAllObjects()
        pointArray.removeAllObjects()
        self.setNeedsDisplay()
    }
    
    func startWithScale(_ scale : Float, _ offsetX : Float, _ offsetY : Float, _ penWidth : Int, _ pointX : Float,_ pointY : Float, _ force : Int ) -> Void {
        debugPrint("startWithScale ")

        if isChangePage {
            hasDraw = true
            let  array : NSMutableArray = NSMutableArray.init()
            array.add(self.strokeColor)
            array.add(NSNumber.init(value: penWidth))
            let point : CGPoint = CGPoint(x: CGFloat( pointX), y:CGFloat( pointY))
            array.add(NSValue(cgPoint: point))
            debugPrint("array cuont = \(array.count)")
            self.pageArray.add(array)
        }else{
            hasDraw = true
            self.penWidth = penWidth
            let  array : NSMutableArray = NSMutableArray.init()
            let point : CGPoint = CGPoint(x: CGFloat( pointX), y:CGFloat( pointY))
            array.add(NSValue(cgPoint: point))
            debugPrint("array cuont = \(array.count)")
            self.pointArray.add(array)
        }
        
    }
    func moveWithScale(_ scale : Float, _ offsetX : Float, _ offsetY : Float, _ penWidth : Int, _ pointX : Float,_ pointY : Float, _ force : Int ) -> Void {
        debugPrint("moveWithScale ")
        if isChangePage {
            let  array : NSMutableArray = pageArray.lastObject as! NSMutableArray
            let point : CGPoint = CGPoint(x: CGFloat( pointX), y:CGFloat( pointY))
            array.add(NSValue(cgPoint: point))
            debugPrint("array cuont = \(array.count)")
            self.setNeedsDisplay()
        }else{
            let  array : NSMutableArray = pointArray.lastObject as! NSMutableArray

            let point : CGPoint = CGPoint(x: CGFloat( pointX), y:CGFloat( pointY))
            array.add(NSValue(cgPoint: point))
            debugPrint("array cuont = \(array.count)")
            self.setNeedsDisplay()
        }
    }
    func endWithScale(_ scale : Float, _ offsetX : Float, _ offsetY : Float, _ penWidth : Int, _ pointX : Float,_ pointY : Float, _ force : Int ) -> Void {
        debugPrint("endWithScale ")

        if isChangePage {
            let  array : NSMutableArray = pageArray.lastObject as! NSMutableArray

            let point : CGPoint = CGPoint(x: CGFloat( pointX), y:CGFloat( pointY))
            array.add(NSValue(cgPoint: point))
            debugPrint("array cuont = \(array.count)")
            self.setNeedsDisplay()
        }else{
            let  array : NSMutableArray = pointArray.lastObject as! NSMutableArray

            let point : CGPoint = CGPoint(x: CGFloat( pointX), y:CGFloat( pointY))
            array.add(NSValue(cgPoint: point))
            debugPrint("array cuont = \(array.count)")
            self.setNeedsDisplay()
        }
    }
    
    func end() -> Void {
        if hasDraw {
            self.snapshotViewFromRect(self.bounds, UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
        }else{
            
        }
    }
    func snapshotViewFromRect(_ rect : CGRect, _ capInsets : UIEdgeInsets) -> Void {
        hasDraw = false
        if (self.delegate != nil) {
            self.delegate?.getDrawImage(nil)
        }
        if isChangePage {
            self.pageArray.removeAllObjects()
            isChangePage = false
        }
    }
    

    
    lazy var pointArray : NSMutableArray = NSMutableArray.init()
    lazy var pageArray : NSMutableArray = NSMutableArray.init()
    var penWidth : Int = 1
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        isChangePage = false
        strokeColor = .black
        penWidth = 1
        hasDraw = false
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        debugPrint("销毁")
    }
    
    
    override func draw(_ rect: CGRect) {
      
        
        if isChangePage {
            if pageArray.count==0 {
                return
            }
            for i : Int in 0..<pageArray.count {
                let arr : NSMutableArray = pageArray.object(at: i) as! NSMutableArray
                if arr.count > 2 {
                    let context : CGContext = UIGraphicsGetCurrentContext()!
                    let color : UIColor = arr.object(at: 0) as! UIColor
                    let width : Int = arr.object(at: 1) as! Int
                    let colorSpace : CGColorSpace = CGColorSpaceCreateDeviceRGB()
                    context.setFillColorSpace(colorSpace)
                    context.setStrokeColorSpace(colorSpace)
                    context.setBlendMode(.copy)
                    context.setStrokeColor(color.cgColor)
                    context.setLineCap(.round)
                    context.setLineJoin(.round)
                    
                    context.setLineWidth(CGFloat( width))
                    
                    let pointValue : NSValue = arr.object(at: 2) as! NSValue
                    let point : CGPoint = pointValue.cgPointValue
                    
                    context.move(to: point)
                    for i : Int in 3..<arr.count {
                        let pointValue : NSValue = arr.object(at: i) as! NSValue
                        let point : CGPoint = pointValue.cgPointValue
                        context.addLine(to: point)
                    }
                    context.strokePath()
                    
                    
                }
                
            }
        }else{
            if pointArray.count==0 {
                return
            }
            let arr : NSArray = pointArray.lastObject as! NSArray
            if arr.count > 2 {
                let context : CGContext = UIGraphicsGetCurrentContext()!
                 let colorSpace : CGColorSpace = CGColorSpaceCreateDeviceRGB()
                context.setFillColorSpace(colorSpace)
                context.setStrokeColorSpace(colorSpace)
                context.setBlendMode(.copy)
                context.setStrokeColor(insideColor.cgColor)
                context.setLineCap(.round)
                context.setLineJoin(.round)
                
                context.setLineWidth(CGFloat( penWidth))
                
                let pointValue : NSValue = arr.object(at: 0) as! NSValue
                let point : CGPoint = pointValue.cgPointValue
                
                context.move(to: point)
                for i : Int in 1..<arr.count {
                    let pointValue : NSValue = arr.object(at: i) as! NSValue
                    let point : CGPoint = pointValue.cgPointValue
                    context.addLine(to: point)
                }
                context.strokePath()
                
                
            }
        }
    }
    
}
